// src/utils/exportImage.ts
import html2canvas from 'html2canvas';

/**
 * 将指定元素导出为图片并下载
 * @param elementRef 要导出的DOM元素引用
 * @param fileName 下载的文件名（不带扩展名）
 * @param options html2canvas配置选项
 */
export const exportToImage = async (
  elementRef: HTMLElement,
  fileName: string = 'export',
  options: any = {}
): Promise<void> => {
  try {
    // 默认配置
    const defaultOptions: any = {
      backgroundColor: '#ffffff',
      scale: 2, // 提高清晰度
      logging: false,
      useCORS: true, // 如果图片是跨域的，需要这个选项
      ...options
    };

    // 生成canvas
    const canvas = await html2canvas(elementRef, defaultOptions);
    
    // 转换为图片并下载
    const image = canvas.toDataURL('image/png', 1.0);
    const link = document.createElement('a');
    link.download = `${fileName}.png`;
    link.href = image;
    link.click();
  } catch (error) {
    console.error('导出图片失败:', error);
    throw error;
  }
};